<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Cache;

/**
 * @property int $id
 * @property string $name
 * @property string $username
 * @property string $email
 * @property string $remember_token
 * @property int $unit_id
 * @property string $room
 * @property string $location
 * @property string $political_status
 * @property int $score
 * @property Carbon $created_at
 * @property Carbon $updated_at
 * @property Collection $test
 * @property WeChatUser $weChatUser
 */
class User extends Authenticatable
{
    use Notifiable;

    // 最大考试次数
    const MAX_TEST_NUMBER = 3;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'username', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * 是否可以参加考试
     *
     * @return bool
     */
    public function canTest()
    {
        // 不限次数
        return true;

        // 没人只能自测 n 次
        // return $this->test()->whereNotNull('submit_at')->count() < self::MAX_TEST_NUMBER;

        // 每天只能自测一次
        // return $this->test()->whereNotNull('submit_at')->where('created_at', '>', Carbon::today())->doesntExist();
    }

    /**
     * 获取进行中的考试
     *
     * @return \Illuminate\Database\Eloquent\Model|Test|null
     */
    public function currentTest()
    {
        return Cache::remember('test_for_user_' . $this->id, 600, function () {
            return $this->test()->whereNull('submit_at')->latest()->first();
        });
    }

    /**
     * 单位
     *
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function unit()
    {
        return $this->belongsTo(Unit::class);
    }

    /**
     * 考试
     *
     * @return \Illuminate\Database\Eloquent\Relations\hasMany
     */
    public function test()
    {
        return $this->hasMany(Test::class);
    }

    /**
     * 微信信息
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function weChatUser()
    {
        return $this->hasOne(WeChatUser::class)->withDefault([
            'nickname' => '微信用户',
            'avatar' => asset('img/avatar.png'),
        ]);
    }
}
